package com.parkcar;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.overlay.DrivingRouteOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.umeng.update.UmengUpdateAgent;
/*import com.umeng.update.UmengUpdateAgent;*/

import java.util.ArrayList;
import java.util.List;

import HttpUtils.HttpParkRequest;
import Modle.ParkItemBean;
import util.BaseActivity;
import util.BaseTools;
import util.BaseUtil;
import util.Constrants;

public class MainActivity extends BaseActivity implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, AMap.OnCameraChangeListener {
    private MapView mapView;
    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private ImageView center_iv;
    private TranslateAnimation mAnimation;
    private LatLng mLatlng;
   /* private RouteSearch routeSearch;
    private DrivingRouteOverlay drivingRouteOverlay;*/
    private List<Marker> markerList = new ArrayList<>();
    private int index;
    private LatLng startLatlng, endLatlng;
    private HttpParkRequest parkListRequest;
    private List<ParkItemBean> parkList = new ArrayList<>();
    private boolean isClick;
    private TextView title_tv, contents_tv, address_tv, navi_tv, book_tv, center_line;
    private RelativeLayout canale_ll, navi_ll, info_ll;
    private Drawable drawable;

    @Override
    protected void setUpui(Bundle arg0) {
        setContentView(R.layout.activity_main);
        setTitleGone(View.GONE);
        UmengUpdateAgent.update(this);
        mapView = (MapView) findViewById(R.id.map);
        center_iv = (ImageView) findViewById(R.id.center_iv);
        mapView.onCreate(arg0);// 必须要写
        aMap = mapView.getMap();
        mAnimation = new TranslateAnimation(center_iv.getX(),
                center_iv.getX(), center_iv.getX() - 50,
                center_iv.getX());
        mAnimation.setDuration(500);
        mAnimation.setRepeatCount(1);
        mAnimation.setFillAfter(false);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                    if(info_ll.getVisibility()==View.VISIBLE){
                        info_ll.setVisibility(View.GONE);
                    }
            }
        });
        initView();
        initLocation();
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
      //  initRount();
    }

    private void initView() {
        title_tv = (TextView) findViewById(R.id.title_tv);
        contents_tv = (TextView) findViewById(R.id.contents_tv);
        address_tv = (TextView) findViewById(R.id.address_tv);
        book_tv = (TextView) findViewById(R.id.book_tv);
        center_line = (TextView) findViewById(R.id.center_line);
        canale_ll = (RelativeLayout) findViewById(R.id.canale_ll);
        navi_ll = (RelativeLayout) findViewById(R.id.navi_ll);
        navi_tv = (TextView) findViewById(R.id.navi_tv);
        info_ll = (RelativeLayout) findViewById(R.id.info_ll);
        drawable = getResources().getDrawable(R.drawable.navigation);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
    }

    /**
     * 路径规划初始化
     */
    private void initRount() {
      /*  routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);*/
    }

    /**
     * 开启定位
     */
    private void initLocation() {
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.drawable.location));
        // 自定义精度范围的圆形边框颜色
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式，参见类AMap。
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        aMap.setOnCameraChangeListener(this);
    }

   /* *//**
     * 初始化marker点
     *//*
    private void initMarker() {
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        //  aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        addMarker();
    }*/

    /**
     * 添加marker
     */
    private void addMarker() {
        for(Marker marker:markerList){
            marker.destroy();
        }
        markerList = new ArrayList<>();
        aMap.clear();
        for (final ParkItemBean bean : parkList) {
            View mView = getLayoutInflater().inflate(R.layout.view_location, null);
            ImageView mimage = (ImageView) mView.findViewById(R.id.park_img);
            TextView mText = (TextView) mView.findViewById(R.id.park_tv);
            if (bean.getCar_park_spare_num() == 0) {
                mimage.setImageResource(R.drawable.park_blue);
                mText.setVisibility(View.GONE);
            } else if (bean.getCar_park_spare_num() < 30) {
                mText.setVisibility(View.VISIBLE);
                mText.setText(bean.getCar_park_spare_num() + "");
                mimage.setImageResource(R.drawable.park_red);
            } else if (bean.getCar_park_spare_num() < 50) {
                mText.setVisibility(View.VISIBLE);
                mText.setText(bean.getCar_park_spare_num() + "");
                mimage.setImageResource(R.drawable.park_yellow);
            } else {
                mText.setVisibility(View.VISIBLE);
                mText.setText(bean.getCar_park_spare_num() + "");
                mimage.setImageResource(R.drawable.park_green);
            }

            MarkerOptions markerOptions = new MarkerOptions().anchor(0.5f, 0.5f).draggable(false)
                    .icon(BitmapDescriptorFactory.fromView(mView))
                    .position(new LatLng(bean.getLatitude(), bean.getLongitude()));
            markerList.add(aMap.addMarker(markerOptions));
        }
    }

    @Override
    protected void updateUI(boolean isLogin) {

    }

    /**
     * 扫描
     *
     * @param view
     */
    public void toSweep(View view) {
        if (!BaseUtil.isLogin(MainActivity.this)) {
            showActivity(LoginActivity.class, null);
        } else {
            showActivity(CaptureActivity.class, null);
        }
    }

    public void toMine(View view) {
        if (!BaseUtil.isLogin(MainActivity.this)) {
            showActivity(LoginActivity.class, null);
        } else {
            showActivity(HomeMineActivity.class, null);
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                //  mLocationErrText.setVisibility(View.GONE);
                startLatlng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                Log.e("zoom", aMap.getCameraPosition().zoom + "");
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(startLatlng, 12));
                Log.e("zoom", aMap.getCameraPosition().zoom + "");
                mlocationClient.stopLocation();
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
              /*  mLocationErrText.setVisibility(View.VISIBLE);
                mLocationErrText.setText(errText);*/
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        isClick = true;
        if (markerList.contains(marker)) {
            index = markerList.indexOf(marker);
            if (index >= 0) {
              /*  RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(startLatlng.latitude, startLatlng.longitude)
                        , new LatLonPoint(marker.getPosition().latitude, marker.getPosition().longitude));
                RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null, null, "");
                routeSearch.calculateDriveRouteAsyn(query);//开始规划路径*/
                info_ll.setVisibility(View.VISIBLE);
                ParkItemBean bean = parkList.get(index);
                endLatlng = new LatLng(bean.getLatitude(), bean.getLongitude());
                title_tv.setText(bean.getName());
                address_tv.setText(bean.getAddress());
                float distance = AMapUtils.calculateLineDistance(startLatlng, new LatLng(bean.getLatitude(), bean.getLongitude()));

                if (distance < 50) {
                    navi_ll.setClickable(false);
                    navi_tv.setCompoundDrawables(null, null, null, null);
                    contents_tv.setText("空车位：" + bean.getCount() + (BaseTools.isValueEmpty(bean.getPrice_desc())?"":" 收费：" +  bean.getPrice_desc()));
                } else {
                    navi_ll.setClickable(true);
                    navi_tv.setCompoundDrawables(drawable, null, null, null);
                    if (distance < 1000) {
                        contents_tv.setText("空车位：" + bean.getCount() + "  距离：" + distance + "m  收费：" + bean.getPrice() + bean.getPrice_desc());
                    } else {
                        distance = distance / 1000;
                        contents_tv.setText("空车位：" + bean.getCount() + "  距离：" + distance + "Km  收费：" + bean.getPrice() + bean.getPrice_desc());
                    }
                }
            }
            mHandle.sendEmptyMessageDelayed(100, 1500);
            return true;
        }
        mHandle.sendEmptyMessageDelayed(100, 1500);
        return false;
    }
    public void toBook(View view) {
        showActivity(OrderTimeActivity.class,null,Constrants.SELECTTIME);
        toast("预订");
    }

    public void toNavi(View view) {
        toast("导航");
        Bundle mbundle = new Bundle();
        mbundle.putDouble("startLat", startLatlng.latitude);
        mbundle.putDouble("startLng", startLatlng.longitude);
        mbundle.putDouble("endLat", endLatlng.latitude);
        mbundle.putDouble("endLng", endLatlng.longitude);
        showActivity(NaviActivity.class, mbundle);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
// 计算量坐标点距离
        if (isClick) {
            return;
        }
        float distance = 0;
        if (mLatlng != null) {
            distance = AMapUtils.calculateLineDistance(mLatlng, cameraPosition.target);
        }
        if (distance > 600 || mLatlng == null) {
            mLatlng = cameraPosition.target;
            Log.e("cameraPosition", cameraPosition.target.latitude + "  " + cameraPosition.target.longitude);
            center_iv.startAnimation(mAnimation);
            getdata();
        }
    }

 /*   @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

    }

    @Override
    public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
        if (rCode == 0) {
            if (result != null && result.getPaths() != null
                    && result.getPaths().size() > 0) {
                DrivePath drivePath = result.getPaths().get(0);
                addMarker();
                drivingRouteOverlay = new DriRount(
                        this, aMap, drivePath, result.getStartPos(),
                        result.getTargetPos());
                drivingRouteOverlay.removeFromMap();
                drivingRouteOverlay.addToMap();
            } else {
                toast(getString(R.string.no_result));
            }
        } else if (rCode == 27) {
            toast(getString(R.string.error_network));
        } else if (rCode == 32) {
            toast(getString(R.string.error_key));
        } else {
            toast(getString(R.string.error_other)
                    + rCode);
        }
        aMap.setOnCameraChangeListener(this);
    }

    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    class DriRount extends DrivingRouteOverlay {

        public DriRount(Context context, AMap aMap, DrivePath drivePath, LatLonPoint latLonPoint, LatLonPoint latLonPoint1) {
            super(context, aMap, drivePath, latLonPoint, latLonPoint1);
        }

        public DriRount(Context context, AMap aMap, DrivePath drivePath, LatLonPoint latLonPoint, LatLonPoint latLonPoint1, List<LatLonPoint> list) {
            super(context, aMap, drivePath, latLonPoint, latLonPoint1, list);
        }

        @Override
        protected void addStartAndEndMarker() {

        }
    }*/

    @Override
    public void httpSuccessListener(Bundle successMsg) {
        super.httpSuccessListener(successMsg);
        if (parkListRequest != null && action.equalsIgnoreCase(parkListRequest.getAction())) {
            if (mBaseResult == null) {
                toast("与服务器失去连接，请稍后重试");
            } else if (mBaseResult.getStatus().getRetCode() == 0) {
                List<ParkItemBean> mList = mBaseResult.toArray(ParkItemBean.class);
                if (BaseTools.isValueEmpty(mList)) {
                    return;
                }
                if (parkList.containsAll(mList)) {
                    return;
                }
                info_ll.setVisibility(View.GONE);
                parkList = mList;
                addMarker();
            } else {
                toast("未搜索到附近5Km内车位信息");
            }
        }
    }

    public void toSearch(View view) {
        showActivity(SearchActivity.class, null, Constrants.SEARCH);
    }

    private void getdata() {
        parkListRequest = new HttpParkRequest(this, 0);
        parkListRequest.getPatkList(mLatlng.latitude + "", mLatlng.longitude + "", 4);
        parkListRequest.setmIHttpClinetListener(this);
        parkListRequest.doRequest();
    }

    public Handler mHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isClick = false;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constrants.SEARCH && resultCode == Constrants.SEARCH) {
            double lat = data.getDoubleExtra("lat", 0);
            double lng = data.getDoubleExtra("lng", 0);
            if (lat != 0) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12));
            }
        }else if(requestCode==Constrants.SELECTTIME&&resultCode==Constrants.SELECTTIME){
            toast("已选");
        }
    }
}
